package main


import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"net/http"
	"database/sql"
)

var (
	DB *gorm.DB
	err error
)

type WebsiteLink struct {
	ID int `json:"id"`
	Name string `json:"name" gorm:"type:varchar(32)"`
	Slink string `json:"slink" gorm:"type:varchar(100)"`
	CategoryId int `json:"category_id" gorm:"type:int(11);default:1"`
}

func GetLinks(c *gin.Context) {
	var linkList []*WebsiteLink
	if err := DB.Debug().Find(&linkList).Error; err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	} else {
		c.JSON(http.StatusOK, linkList)
	}
}

func GetALink(id string) (link WebsiteLink){
	err := DB.Debug().Where("id=?", id).First(&link).Error
	if err != nil {
		fmt.Println(err)
	}
	return link
}

func UpdateLink(c *gin.Context){
	id, ok := c.Params.Get("id")
	if !ok {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	}

	link := GetALink(id)
	fmt.Printf("%T\n", link)
	fmt.Printf("%v\n", link)
	c.BindJSON(&link)

	err = DB.Save(link).Error
	fmt.Println(err)
}

func main() {

	dsn := "root:root@(127.0.0.1)/site?charset=utf8mb4&parseTime=True&loc=Local"
	DB, err = gorm.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}

	DB.SingularTable(true)

	r := gin.Default()

	r.GET("/links", GetLinks)
	r.PUT("/link/:id", UpdateLink)

	r.Run(":9100")
}
